<template>
  <div>
    <!-- 内容区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="i in cateList" :label="i.cate_name" :value="i.id" :key="i.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="choseFn">筛选</el-button>
            <el-button type="info" size="small" @click="resetFn">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialogFn">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="scope">
            <el-link typeof="primary" @click="showDetaIlFn(scope.row.id)">
              {{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="{ row }">
            <span>{{ $formatDate(row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="removeFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChangeFn" @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size.sync="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 发表文章的对话框 -->
    <el-dialog @close="dialogCloseFn" title="发表文章" :visible.sync="pubDialogVisible" fullscreen
      :before-close="handleClose">
      <!-- 发布文章的对话框 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="i in cateList" :label="i.cate_name" :value="i.id" :key="i.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor @change="contentChangeFn" v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img @click="selCoverFn" src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none" @change="changeCoverFn" accept="image/*" ref="iptFileRef" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="selCoverFn">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticleFn('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticleFn('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ $formatDate(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 文章的封面 -->
      <img v-if="artDetail.cover_img" :src="baseURLr + artDetail.cover_img" alt="" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import { baseURL } from '@/utils/request'
import {
  getArtCateListAPI,
  uploadArticleAPI,
  getArticleListAPI,
  getArticleDetailFn,
  delArtAPI
} from '@/api'
import defaultImg from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  data () {
    return {
      baseURLr: baseURL,
      // 查询参数对象
      q: {
        pagenum: 1, // 默认拿第一页的数据
        pagesize: 2, // 默认当前页需要的数据条数
        cate_id: '',
        state: ''
      },
      pubDialogVisible: false, // 控制发布文章对话框的显示隐藏
      pubForm: {
        // 表单的数据对象
        title: '', // 文章的标题
        cate_id: '', // 文章分类的id
        content: '', // 文章的内容
        cover_img: '', // 封面文件
        state: '' // 文章的发布状态，可选值有两个：草稿、已发布
      },
      pubFormRules: {
        // 表单的验证规则对象
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请选择文章内容', trigger: 'blur' }
        ],
        cover_img: [{ required: true, message: '请选择封面', trigger: 'blur' }]
      },
      cateList: [], // 保存文章分类列表
      artList: [], // 文章的列表数据
      total: 0, // 总数据条数
      detailVisible: false, // 显示隐藏文章详情对话框
      artDetail: {} // 保存文章详情
    }
  },
  mounted () {
    this.getCateListFn()
    this.getArticleListFn()
  },
  methods: {
    // 删除按钮点击
    async removeFn (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 2. 取消了删除
      if (confirmResult === 'cancel') return
      // 执行删除的操作
      const { data: res } = await delArtAPI(id)
      if (res.code !== 0) return this.$message.error('删除失败!')
      this.$message.success('删除成功!')
      // 刷新列表数据
      if (this.artList.length === 1) {
        if (this.q.pagenum > 1) {
          this.q.pagenum--
        }
      }
      this.getArticleListFn()
    },
    // 文章标题的点击事件
    async showDetaIlFn (artId) {
      const res = await getArticleDetailFn(artId)
      if (res.data.code === 0) {
        this.artDetail = res.data.data
        this.detailVisible = true
      } else {
        this.$message.error(res.data.data.message)
      }
    },
    // 重置按钮
    resetFn () {
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.q.cate_id = ''
      this.q.state = ''
      this.getArticleListFn()
    },
    // 筛选按钮
    choseFn () {
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.getArticleListFn()
    },
    // 分页每页条数改变
    handleSizeChangeFn (sizes) {
      // 用于解决bug，第二页没数据
      this.q.pagenum = 1
      this.q.pagesize = sizes
      this.getArticleListFn()
    },
    // 当前页码改变
    handleCurrentChangeFn (nowPage) {
      this.q.pagenum = nowPage
      this.getArticleListFn()
    },
    // 获取文章列表
    async getArticleListFn () {
      const res = await getArticleListAPI(this.q)
      if (res.data.code === 0) {
        this.total = res.data.total
        this.artList = res.data.data
      }
    },
    // 新增文章后关闭表单清空表单
    dialogCloseFn () {
      this.$refs.pubFormRef.resetFields()
      // 重置封面图片
      this.$refs.imgRef.setAttribute('src', defaultImg)
    },
    // 富文本编辑器change方法
    contentChangeFn () {
      this.$refs.pubFormRef.validateField('content')
    },
    // 发布和存草稿的方法
    pubArticleFn (state) {
      // 1. 设置发布状态
      this.pubForm.state = state
      // 2. 表单预校验
      this.$refs.pubFormRef.validate(async (valid) => {
        if (valid) {
          const fd = new FormData()
          fd.append('title', this.pubForm.title)
          fd.append('cate_id', this.pubForm.cate_id)
          fd.append('content', this.pubForm.content)
          fd.append('cover_img', this.pubForm.cover_img)
          fd.append('state', this.pubForm.state)
          const res = await uploadArticleAPI(fd)
          if (res.data.code === 0) {
            this.$message.success(res.data.message)
          } else {
            this.$message.error(res.data.message)
          }
          this.pubDialogVisible = false
          this.getArticleListFn()
        } else {
          return false
        }
      })
    },
    // 用户选择了封面文件
    changeCoverFn (e) {
      // 获取用户选择的文件列表
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
        this.pubForm.cover_img = null
        // 显示默认图片
        this.$refs.imgRef.setAttribute('src', defaultImg)
      } else {
        // 用户选择了封面
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      }
      this.$refs.pubFormRef.validateField('cover_img')
    },
    // 添加文章封面
    selCoverFn () {
      this.$refs.iptFileRef.click()
    },
    // 请求分类数据
    async getCateListFn () {
      const res = await getArtCateListAPI()
      if (res.data.code === 0) {
        this.cateList = res.data.data
      }
    },
    // 发布文章对话框关闭前回调
    async handleClose (done) {
      const confirmResult = await this.$confirm(
        '此操作将导致文章信息丢失, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 取消了关闭-阻止住, 什么都不干
      if (confirmResult === 'cancel') return
      // 确认关闭
      done()
    },
    // 发表文章按钮->点击事件->让添加文章对话框出现
    showPubDialogFn () {
      this.pubDialogVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;

  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
::v-deep .detail-box {
  img {
    width: 500px;
  }
}

.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

::v-deep .ql-editor {
  min-height: 300px;
}

.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .btn-pub {
    margin-top: 5px;
  }
}
</style>
